package utils;

import java.io.IOException;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json的转换
 */
public class JsonUtil {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();
    static {
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        MAPPER.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
//        MAPPER.configure(DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS, false);
        //MAPPER.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES,true);//大小写脱敏 默认为false  需要改为true
        //System.out.println("init");

    }


    /**
     * 将对象转换成Json字符串。
     * @param pojo
     * @return
     */
    public static String Pojo2Json(Object pojo) {
        try {
            String string = MAPPER.writeValueAsString(pojo);
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将Json结果集转化为对象
     * @param jsonData json数据
     * @param beanType 对象中的object类型
     * @return
     */
    public static <T> T Json2Pojo(String jsonData, Class<T> beanType) throws IOException {
        T t = MAPPER.readValue(jsonData, beanType);
        return t;
    }

    /**
     * 将Json数据转换成Pojo对象List
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> Json2PojoList(String jsonData, Class<T> beanType){
        System.out.println("转化");
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = MAPPER.readValue(jsonData, javaType);
            return list;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}